package com.ipan.weixin.msg.general;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 自定义菜单事件
 * 
 * @author iPan
 * @version 2013-12-23
 */
public class DefineMenusMsg extends EventMsg {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1803645539012522472L;

	/** 事件KEY值，与自定义菜单接口中KEY值对应 */
	protected String eventKey;
	
	public DefineMenusMsg() {
		super(TransportType.RECEIVE);
	}
	
	public DefineMenusMsg(Document doc) {
		this();
		fromXml(doc);
	}

	public String getEventKey() {
		return eventKey;
	}

	public void setEventKey(String eventKey) {
		this.eventKey = eventKey;
	}

	@Override
	public void fromXml(Document doc) {
		if (doc == null) {
			return ;
		}
		
		super.fromXml(doc);
		Element root = doc.getRootElement();
		this.eventKey = root.elementTextTrim(EL_EVENT_KEY);
	}
	
	@Override
	public String toXml(boolean nonEmpty) {
		StringBuilder buf = new StringBuilder("<xml>");
		buf.append(super.toXml(nonEmpty));
		buf.append(wrapElementHead(EL_MSG_TYPE)).append(TYPE_EVENT).append(wrapElementEnd(EL_MSG_TYPE));
		if (nonEmpty) {
			if (StringUtils.isNotEmpty(this.eventKey)) {
				buf.append(wrapElementHead(EL_EVENT_KEY)).append(this.eventKey).append(wrapElementEnd(EL_EVENT_KEY));
			}
		} else {
			buf.append(wrapElementHead(EL_EVENT_KEY)).append(getStringValue(this.eventKey)).append(wrapElementEnd(EL_EVENT_KEY));
		}
		return buf.append("</xml>").toString();
	}
}

/*
接收：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[CLICK]]></Event>
<EventKey><![CDATA[EVENTKEY]]></EventKey>
</xml>
*/
